package xdu.lz.netty.f_netty_buf;

import org.junit.Test;

import java.util.concurrent.atomic.AtomicIntegerFieldUpdater;

/**
 * @author lizhen
 * @date 2019/8/21 16:21
 * @desc
 */
public class AtomicUpdateTest {

    public static void main(String[] args) {
        Person person = new Person();
//        for (int i = 0; i < 10 ; i++) {
//            Thread thread = new Thread(()->{
//                try {
//                    Thread.sleep(20L);
//                } catch (InterruptedException e) {
//                    e.printStackTrace();
//                }
//                System.out.println(person.age++);//执行两部，先打印age，再++ ，可能会出现线程安全问题
//            });
//            thread.start();
//        }

        AtomicIntegerFieldUpdater<Person> fieldUpdater =
                AtomicIntegerFieldUpdater.newUpdater(Person.class, "age");
        for (int i = 0; i < 10 ; i++) {
            Thread thread = new Thread(()->{
                try {
                    Thread.sleep(20L);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println(fieldUpdater.getAndIncrement(person));
            });
            thread.start();
        }
    }




}

class Person{
//    static volatile int age = 1; //sun.misc.Unsafe.objectFieldOffset(Native Method)不支持static方法
    volatile int age = 1;
}